<template>
  <div class="square-container">
    <!-- 顶部标题和发布按钮 -->
    <div class="square-header">
      <h2 class="title">小区广场动态</h2>
      <el-button 
        type="primary" 
        @click="showPublishDialog = true"
        class="publish-btn"
      >
        <el-icon><Plus /></el-icon> 发布动态
      </el-button>
    </div>

    <!-- 动态发布对话框 -->
    <el-dialog 
      v-model="showPublishDialog" 
      title="发布新动态" 
      width="60%"
    >
      <el-form :model="publishForm" label-width="80px">
        <el-form-item label="动态内容">
          <el-input
            v-model="publishForm.content"
            type="textarea"
            :rows="4"
            placeholder="分享您的最新动态..."
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="3"
            :on-change="handleUploadChange"
            :on-remove="handleRemove"
            :file-list="publishForm.images"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPublishDialog = false">取消</el-button>
        <el-button type="primary" @click="handlePublish" :loading="publishing">发布</el-button>
      </template>
    </el-dialog>

    <!-- 动态列表 -->
    <div class="dynamic-list">
      <el-card 
        v-for="(item, index) in dynamicList" 
        :key="item.dynamicId"
        class="dynamic-item"
      >
        <template #header>
          <div class="dynamic-header">
            <div class="user-info">
              <el-avatar :size="40" :src="item.avatar" />
              <div class="user-detail">
                <span class="username">{{ item.username }}</span>
                <span class="time">{{ formatTime(item.createTime) }}</span>
              </div>
            </div>
            <!-- 修正：确保type属性有有效值 -->
            <el-tag :type="item.type === 'official' ? 'success' : 'info'">
              {{ item.type === 'official' ? '官方' : '业主' }}
            </el-tag>
          </div>
        </template>
        <div class="dynamic-content">
          {{ item.content }}
        </div>
        <!-- 修正：确保images存在且正确处理 -->
        <div v-if="item.images && item.images.split(',').filter(img => img).length > 0" class="dynamic-images">
          <el-image
            v-for="(img, i) in item.images.split(',').filter(img => img)"
            :key="i"
            :src="img"
            :preview-src-list="item.images.split(',').filter(img => img)"
            fit="cover"
            class="image-item"
          />
        </div>
        <div class="dynamic-actions">
          <el-button 
            text 
            :icon="item.isLiked ? StarFilled : Star" 
            @click="toggleLike(item.dynamicId, index)"
            :loading="likeLoading[index]"
          >
            {{ item.likeCount || 0 }}
          </el-button>
          <el-button 
            text 
            :icon="ChatDotRound" 
            @click="focusComment(index)"
            :loading="commentLoading[index]"
          >
            评论 {{ item.commentCount || 0 }}
          </el-button>
        </div>
        
        <!-- 评论区域 -->
        <div v-if="activeComment === index" class="comment-section">
          <div class="comment-list">
            <div v-for="(comment, cIndex) in item.comments" :key="cIndex" class="comment-item">
              <el-avatar :size="32" :src="comment.avatar" />
              <div class="comment-content">
                <div class="comment-user">{{ comment.username }}</div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
              </div>
            </div>
            <el-empty v-if="!item.comments || item.comments.length === 0" description="暂无评论" :image-size="50" />
          </div>
          <div class="comment-input">
            <el-input
              v-model="commentText[index]"
              placeholder="写下你的评论..."
              @keyup.enter="submitComment(item.dynamicId, index)"
            >
              <template #append>
                <el-button @click="submitComment(item.dynamicId, index)">发送</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </el-card>
      
      <!-- 加载更多 -->
      <div class="load-more">
        <el-button 
          v-if="!loading && hasMore" 
          @click="fetchDynamicList(true)" 
          :loading="loadingMore"
        >
          加载更多
        </el-button>
        <div v-if="!hasMore" class="no-more">没有更多动态了</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { 
  Plus, 
  Star, 
  StarFilled, 
  ChatDotRound
} from '@element-plus/icons-vue'
import { formatTime } from '@/util/timeFormat'
import { squarelist, publishDynamic, likeDynamic, addComment } from '@/util/request'
import { useCounterStore } from '@/stores/counter'
import { ElMessage } from 'element-plus'

const store = useCounterStore()
const route = useRoute()

// 检查当前路由是否是动态交流页面
const isSquarePage = computed(() => route.path === '/square')

// 监听路由变化，当进入动态交流页面时加载数据
watch(() => route.path, (newPath) => {
  if (newPath === '/square') {
    fetchDynamicList()
  }
})

// 检查用户是否登录
const isLoggedIn = computed(() => store.isAuthenticated && !!JSON.parse(store.userInfo).id)
// console.log(" useCounterStore:",store.isAuthenticated,JSON.parse(store.userInfo).id)
// console.log("当前用户userInfo:", JSON.parse(store.userInfo))
// console.log("当前用户是否登录:", isLoggedIn.value)

// 发布对话框状态
const showPublishDialog = ref(false)
const publishForm = ref({
  content: '',
  images: []
})
const publishing = ref(false)

// 动态列表数据
const dynamicList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const pageParams = ref({
  page: 1,
  size: 10
})

// 评论相关状态
const activeComment = ref(null)
const commentText = ref([])
const commentLoading = ref({})
const likeLoading = ref({})

// 图片上传处理
const handleUploadChange = (file) => {
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.warning('图片大小不能超过2MB')
    return false
  }
  publishForm.value.images.push(file)
}

const handleRemove = (file) => {
  const index = publishForm.value.images.findIndex(
    img => img.uid === file.uid
  )
  if (index !== -1) {
    publishForm.value.images.splice(index, 1)
  }
}

// 获取动态列表
const fetchDynamicList = async (isLoadMore = false) => {
  if (loading.value || (isLoadMore && !hasMore.value)) return
  
  try {
    if (isLoadMore) {
      loadingMore.value = true
      pageParams.value.page++
    } else {
      loading.value = true
      pageParams.value.page = 1 // 重置页码
    }
    
    const res = await squarelist({ 
      page: pageParams.value.page, 
      size: pageParams.value.size 
    })
    console.log("API返回数据:", res.data)
    
    // 修正：使用正确的数据结构
    const dynamicData = res.data.data?.dynamics || []
    
    if (dynamicData.length > 0) {
      const formattedData = dynamicData.map(item => ({
        ...item,
        id: item.dynamicId,  // 确保使用正确的ID字段
        username: item.username || '匿名用户',
        avatar: item.avatar || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
        type: item.type || 'owner', // 确保type有默认值
        images: item.images || '',
        isLiked: item.isLiked || false,
        likeCount: item.likeCount || 0,
        commentCount: item.commentCount || 0,
        comments: item.comments || []
      }))
      
      console.log("格式化后的数据:", formattedData)
      
      if (isLoadMore) {
        dynamicList.value = [...dynamicList.value, ...formattedData]
      } else {
        dynamicList.value = formattedData
      }
      
      hasMore.value = dynamicData.length >= pageParams.value.size
    } else {
      hasMore.value = false
      if (!isLoadMore) {
        dynamicList.value = []
      }
    }
  } catch (error) {
    ElMessage.error('获取动态列表失败')
    console.error('获取动态列表错误:', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 发布动态方法
const handlePublish = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }

  if (!publishForm.value.content.trim()) {
    ElMessage.warning('请填写动态内容')
    return
  }

  try {
    publishing.value = true
    
    // 修正：使用正确的数据结构
    const res = await publishDynamic({
      userId: JSON.parse(store.userInfo).id,
      content: publishForm.value.content,
      images: publishForm.value.images.map(file => file.url || URL.createObjectURL(file.raw || file))
    })
    
    const newDynamic = {
      ...res.data,
      username: store.userInfo.username,
      avatar: store.userInfo.avatar,
      type: 'owner',
      isLiked: false,
      likeCount: 0,
      commentCount: 0,
      comments: []
    }
    
    dynamicList.value.unshift(newDynamic)
    showPublishDialog.value = false
    publishForm.value = { content: '', images: [] }
    ElMessage.success('动态发布成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '发布动态失败')
    console.error(error)
  } finally {
    publishing.value = false
  }
}

// 点赞处理
const toggleLike = async (dynamicId, index) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    likeLoading.value[index] = true
    const res = await likeDynamic({
      dynamicId,
      userId: store.userId
    })
    
    const item = dynamicList.value[index]
    item.isLiked = !item.isLiked
    item.likeCount = item.isLiked ? (item.likeCount || 0) + 1 : (item.likeCount || 0) - 1
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
    console.error(error)
  } finally {
    likeLoading.value[index] = false
  }
}

// 评论处理
const focusComment = (index) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  activeComment.value = activeComment.value === index ? null : index
  commentText.value[index] = ''
  
  if (activeComment.value === index && (!dynamicList.value[index].comments || dynamicList.value[index].comments.length === 0)) {
    loadComments(dynamicList.value[index].dynamicId, index)
  }
}

const loadComments = async (dynamicId, index) => {
  try {
    commentLoading.value[index] = true
    const res = await squarelist({
      dynamic_id: dynamicId,
      page: 1,
      size: 10
    })
    
    if (res.data?.list) {
      dynamicList.value[index].comments = res.data.list.map(comment => ({
        ...comment,
        username: comment.username || '匿名用户',
        avatar: comment.avatar || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
      }))
    }
  } catch (error) {
    console.error('加载评论失败', error)
  } finally {
    commentLoading.value[index] = false
  }
}

const submitComment = async (dynamicId, index) => {
  if (!commentText.value[index]?.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }

  try {
    const res = await addComment({
      dynamicId,
      content: commentText.value[index],
      userId: store.userId
    })
    
    dynamicList.value[index].comments.unshift({
      ...res.data,
      username: store.userInfo.username,
      avatar: store.userInfo.avatar
    })
    
    dynamicList.value[index].commentCount = (dynamicList.value[index].commentCount || 0) + 1
    commentText.value[index] = ''
    ElMessage.success('评论成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '发表评论失败')
    console.error(error)
  }
}

// 初始化加载数据 - 只有当当前页面是动态交流页面时才加载
onMounted(() => {
  if (isSquarePage.value) {
    fetchDynamicList()
  }
})
</script>

<style scoped>
/* 原有样式保持不变 */
.square-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.square-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .title {
    color: #333;
    margin: 0;
  }
}

.dynamic-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.dynamic-item {
  border-radius: 8px;
  
  :deep(.el-card__header) {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.dynamic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .user-detail {
      display: flex;
      flex-direction: column;
      
      .username {
        font-weight: bold;
        font-size: 14px;
      }
      
      .time {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.dynamic-content {
  margin: 10px 0;
  line-height: 1.6;
  white-space: pre-line;
}

.dynamic-images {
  display: flex;
  gap: 10px;
  margin: 15px 0;
  flex-wrap: wrap;
  
  .image-item {
    width: 120px;
    height: 120px;
    border-radius: 4px;
    cursor: pointer;
    object-fit: cover;
  }
}

.dynamic-actions {
  display: flex;
  gap: 15px;
  margin-top: 15px;
  
  .el-button {
    padding: 0;
  }
}

.comment-section {
  margin-top: 20px;
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.comment-list {
  margin-bottom: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.comment-item {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  
  .comment-content {
    flex: 1;
    
    .comment-user {
      font-weight: bold;
      font-size: 13px;
      margin-bottom: 4px;
    }
    
    .comment-text {
      font-size: 14px;
      line-height: 1.5;
    }
    
    .comment-time {
      font-size: 12px;
      color: #999;
      margin-top: 2px;
    }
  }
}

.comment-input {
  margin-top: 15px;
}

.load-more {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  
  .no-more {
    color: #999;
    font-size: 14px;
    padding: 10px 0;
  }
}
</style>